<template>
  <el-image :style="imgStyle" :src="url" :preview-src-list="srcList">
  </el-image>
</template>
<script>
export default {
  props: {
    fileList: {
      type: Array,
      default: [],
    },
    imgStyle: {
      type: String,
      default: "width: 100px; height: 100px",
    },
  },
  data() {
    return {
      url: "",
      srcList: [],
    };
  },
  methods: {
    init() {
      let fileList = this.fileList;
      let srcList = [];
      if (this.isJSON(fileList)) {
        let url = JSON.parse(fileList)[0].url || "";
        srcList.push(url);
        this.url = url;
        this.srcList = srcList;
      } else {
        if (Array.isArray(fileList)) {
          fileList.map((item) => {
            if (item.type == 0) {
              let url = "";
              if (item.url) {
                url = this.isJSON(item.url)
                  ? JSON.parse(item.url)[0].url
                  : item.url;
              }
              this.url = url;
              srcList.push(url);
            }
          });
          this.srcList = srcList;
        } else {
          this.url = "";
          this.srcList = [""];
        }
      }
    },
    isJSON(str) {
      if (typeof str == "string") {
        try {
          JSON.parse(str);
          return true;
        } catch (e) {
          return false;
        }
      }
    },
  },
  created() {
    this.init();
  },
  watch: {
    fileList: {
      handler: function (newValue, oldValue) {
        // if (newValue !== oldValue) {
        this.init();
        // }
      },
      deep: true,
    },
  },
};
</script>
